<script setup lang="ts">
import logo from '@/assets/logo.png'
import { useGlobalStore } from '@/stores/global'
import { getRoleInfo, logoutUser } from '@/api/system/common'
import router, { addRouter } from '@/router'
import { useRoleInfoStore } from '@/stores/roleInfo'
import { onMounted, ref } from 'vue'
import MenuItemComponent from '@/components/MenuItemComponent.vue'
import { Message } from '@arco-design/web-vue'
import { useTabStore } from '@/stores/tabs'
import { getGlobalCache, refreshGlobalCacheValue } from '@/api/system/cache'

//切换主题
const globalStore = useGlobalStore()
const toggleTheme = () => {
  //切换主题
  globalStore.global.theme = !globalStore.global.theme
  if (!globalStore.global.theme) {
    // 恢复亮色主题
    document.body.removeAttribute('arco-theme')
    document.documentElement.classList.remove('dark')
    return
  }
  // 设置为暗黑主题
  document.body.setAttribute('arco-theme', 'dark')
  document.documentElement.classList.add('dark')
}

// 刷新全局缓存
const refreshGlobalCache = () => {
  getGlobalCache().then(resp => {
    const caches = resp.data
    for (let key in caches) {
      caches[key] = JSON.parse(caches[key])
    }
    console.log(caches)
    globalStore.setCache(caches)
  })
}


//菜单
const menus = ref([] as any[])
//菜单转换
const convertToMenus = () => {
  const routers = roleInfoStore.userInfo.routers

  const menuMap = new Map()
  routers.forEach(val => {
    delete val.children
    menuMap.set(val.id, val)
  })


  routers.forEach(val => {
    //如果没有上级id
    if (!val.parentId || val.parentId == 0) return
    //存在上级id
    const parentVal = menuMap.get(val.parentId)
    //不存在则返回
    if (!parentVal) return
    //没有存在这个字段信息则添加
    if (!parentVal['children']) {
      parentVal['children'] = []
    }
    parentVal['children'].push(val)
  })

  //将菜单信息添加到渲染菜单中
  menus.value = routers.filter((val: any) => val.parentId == 0)
  menus.value.sort((a, b) => a.weight - b.weight)
}

//切换角色
const roleInfoStore = useRoleInfoStore()
const roles = globalStore.global.userInfo.roles
const toggleRole = (index = 0) => {
  //没有角色
  if (roles.length == 0) {
    Message.error('管理员未分配角色')
    return
  }
  //获取角色对应菜单权限列表
  getRoleInfo(roles[index].id).then(resp => {
    console.log(resp.data)
    const routers = resp.data.routers
    //设置到状态中
    roleInfoStore.setUserInfo(resp.data)
    //添加到路由
    addRouter(routers)
    //菜单转换
    convertToMenus()
    Message.success(`欢迎回家！${resp.data.name}`)
    tabStore.reset()
    router.replace('/')
  })
}

//挂载页面之后
onMounted(() => {
  //挂载页面之后选择
  if (!roleInfoStore.userInfo.id) {
    //如果store中没有体现出用户，则是第一次进入需要手动选择用户，则选择第一个角色
    toggleRole()
    return
  }

  //切换到角色菜单
  convertToMenus()

  //刷新全局缓存，首次加载
  refreshGlobalCache()
})

//退出登录
const logout = () => {
  logoutUser().then(() => {
    //清除所有缓存
    globalStore.reset()
    tabStore.reset()
    roleInfoStore.reset()
    localStorage.clear()
    router.push('/login')
  })
}

//记录tab的标签
const tabStore = useTabStore()
const deleteTab = (key: string | number, ev: Event) => {
  tabStore.removeTab(key)
  //删除其他标签
  if (tabStore.tabs.active != key && tabStore.tabs.tabs.length != 0) {
    return
  }
  //当前显示的标签被删除
  const tabs = tabStore.tabs.tabs
  if (tabs.length != 0) {
    router.push(tabs[tabs.length - 1].uri)
    return
  }

  //显示首页信息
  router.push('/')
}
const navigateTo = (key: string | number, ev: Event) => {
  console.log(key)
  if (key == 'home') {
    tabStore.tabs.active = key
    //没有找到则显示主页
    router.push('/')
    return
  }
  for (let i = 0; i < tabStore.tabs.tabs.length; i++) {
    const tab = tabStore.tabs.tabs[i]
    if (tab.id == key) {
      router.push(tab.uri)
      return
    }
  }
}
</script>
<template>
  <a-layout class="bg-slate-100 h-full w-full">
    <!-- 头部-->
    <a-layout-header class="bg-white  border-slate-100 dark:border-slate-800 border-0 border-b border-solid">
      <div class="h-full flex items-center justify-between px-6">
        <div class="flex items-center">
          <a-avatar :image-url="logo" />
          <span class="text-2xl ms-3 dark:text-white">Rocc.cc</span>
        </div>
        <div class="flex items-center">
          <a-tooltip content="刷新全局缓存">
            <a-button class="me-4" shape="circle" size="large" @click="refreshGlobalCache">
              <template #icon>
                <icon-refresh />
              </template>
            </a-button>
          </a-tooltip>
          <a-tooltip content="切换主题">
            <a-button class="me-4" shape="circle" size="large" @click="toggleTheme">
              <template #icon>
                <icon-sun-fill />
              </template>
            </a-button>
          </a-tooltip>
          <a-button shape="circle" class="me-4" size="large">
            <template #icon>
              <icon-notification />
            </template>
          </a-button>
          <a-popover content-style="padding:4px" position="br">
            <div class="cursor-default bg-transparent">
              <a-avatar :image-url="globalStore.global.userInfo.avatarUrl || logo" />
              <span class="ms-2 dark:text-white">{{ globalStore.global.userInfo.nickName }}</span>
              <icon-down class="ms-3 dark:text-white" />
            </div>
            <template #content>
              <a-doption>
                <template #icon>
                  <icon-user />
                </template>
                个人中心
              </a-doption>
              <a-doption v-for="(v,i) in globalStore.global.userInfo.roles" :key="i" @click="toggleRole(i)">
                <template #icon>
                  <icon-sync />
                </template>
                切换 [{{ v.name }}]
              </a-doption>
              <a-doption @click="logout">
                <template #icon>
                  <icon-import />
                </template>
                退出
              </a-doption>
            </template>
          </a-popover>
        </div>
      </div>
    </a-layout-header>
    <a-layout>
      <!-- 菜单 -->
      <a-layout-sider>
        <a-menu>
          <a-menu-item @click="navigateTo('home')">
            <template #icon>
              <icon-home />
            </template>
            主页
          </a-menu-item>
          <MenuItemComponent :menus="menus" />
        </a-menu>
      </a-layout-sider>

      <!-- 内容部分 -->
      <a-layout>
        <a-layout-content class="flex flex-col">
          <a-tabs class="w-full" v-model:active-key="tabStore.tabs.active" @delete="deleteTab"
                  @tab-click="navigateTo"
                  editable>
            <a-tab-pane :closable="false" key="home">
              <template #title>
                <icon-home />
                主页
              </template>
            </a-tab-pane>
            <a-tab-pane v-for="(v) in tabStore.tabs.tabs" :key="v.id">
              <template #title>
                <component :is="v.icon" />
                {{ v.name }}
              </template>
            </a-tab-pane>
          </a-tabs>
          <a-scrollbar outer-class="flex-1" class="h-full rounded-md mt-1 box-border px-5">
            <router-view class="rounded-md"></router-view>
          </a-scrollbar>
        </a-layout-content>
        <a-layout-footer class="h-8 flex items-center  justify-center dark:text-gray-500 text-slate-500">
          dpengchen@163.com &nbsp;&nbsp; 金钱只是一串数字，数据只是一行代码！
        </a-layout-footer>
      </a-layout>
    </a-layout>
  </a-layout>
</template>

<style lang="scss" scoped>

.arco-layout-header {
  height: 64px
}

:deep(.arco-layout-header) {
  background: var(--color-bg-2);
}

.arco-layout {
  background: var(--color-bg-5);
}


</style>
